﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using System.Reflection;
using System.Reflection.Emit;
using System.Windows.Data;
using System.Windows.Controls;

namespace Invini.Training
{
    public class PasswordTrigger : TrainingTriggerBase
    {
        private class ActivePassword
        {
            private PasswordBox passwordBox;
            private RoutedEventHandler handler;

            public ActivePassword(PasswordBox passwordBox, RoutedEventHandler handler)
            {
                this.passwordBox = passwordBox;
                this.handler = handler;
            }
            public void Clear()
            {
                this.passwordBox.PasswordChanged -= this.handler;
            }
        }

        public PathComponentsCollection Element
        {
            get;
            set;
        }
        public string Password
        {
            get;
            set;
        }

        private List<ActivePassword> activePasswords;

        public PasswordTrigger()
        {
            this.Element = new PathComponentsCollection();
        }
        public override void Prepare()
        {
            base.Prepare();

            if (this.Element == null)
                return;

            IEnumerable<object> objects = this.Element.FindElements();
            if (objects.Count() == 0)
                return;

            this.activePasswords = new List<ActivePassword>();

            foreach (object obj in objects)
            {
                PasswordBox passwordBox = obj as PasswordBox;
                if (passwordBox == null)
                    continue;

                if(passwordBox.Password == this.Password)
                {
                    this.IsConditionSatisfied = true;
                    return;
                }

                RoutedEventHandler handler = new RoutedEventHandler(this.passwordBox_PasswordChanged);
                passwordBox.PasswordChanged += handler;

                this.activePasswords.Add(new ActivePassword(passwordBox, handler));
            }
        }

        public override void Clear()
        {
            base.Clear();

            if(this.activePasswords != null)
            {
                foreach (ActivePassword activePassword in this.activePasswords)
                    activePassword.Clear();

                this.activePasswords = null;
            }
        }

        private void passwordBox_PasswordChanged(object sender, RoutedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            if (passwordBox == null)
                return;

            if (passwordBox.Password == this.Password)
                this.IsConditionSatisfied = true;
        }
    }
}
